import React from 'react';
import ReactModal from 'react-modal';

import { BackButton } from '@/features/BackButton';
import { useChangeRoute, useMetaTag, useScrollLock } from '@/shared/lib/hooks';
import { Container, Modal, Wrapper } from '@/shared/ui';
import { Footer } from '@/widgets/Footer';
import { Header } from '@/widgets/Header';
import cn from 'classnames';
import { useWindowSize } from 'usehooks-ts';

import cs from './ModalPage.module.scss';

export const ModalPage = ({
  isOpen,
  handleClose: handleCloseModal,
  children,
  className,
  withFooter,
  noPadding,
  withGoBack,
  handleGoBack,
  crossWithShadow,
  containerClassName,
  zIndex,
  isMobile = true,
}: {
  isMobile?: boolean;
  isOpen?: boolean;
  zIndex?: number;
  withGoBack?: boolean;
  noPadding?: boolean;
  crossWithShadow?: boolean;
  containerClassName?: string;
  handleGoBack?: () => void;
  withFooter?: boolean;
  handleClose?: () => void;
  className?: string;
} & React.PropsWithChildren) => {
  const { lock, unlock } = useScrollLock();
  const { width } = useWindowSize();
  const handleClose = handleCloseModal ?? (() => {});
  useChangeRoute(handleClose);

  React.useEffect(() => {
    lock();
    return () => unlock();
  }, []);

  // скрываем хедер "родительский" со страницы
  React.useEffect(() => {
    if (width > 1024) {
      return;
    }

    const headerToHide = document.querySelector('header:not(#modal-react header)');
    if (headerToHide && isOpen) {
      // @ts-ignore
      headerToHide.style.display = 'none';
    }
    return () => {
      const headers = document.querySelectorAll('header');
      headers.forEach((header) => {
        header.style.display = 'block';
      });
    };
  }, [width, isOpen]);

  // useMetaTag(width < 1024, 'white');

  return width < 1024 ? (
    <ReactModal
      ariaHideApp={false}
      className={cn(cs.modal, className, isMobile && cs.mobile)}
      id="modal-react"
      isOpen={isOpen as boolean}
      onRequestClose={() => handleClose()}
      portalClassName={cn(isMobile && cs.mobile)}
      preventScroll={false}
      shouldCloseOnOverlayClick={false}
      style={{ overlay: { zIndex: zIndex || 1 } }}
    >
      <Header className={cs.header} scrollingElementSelector="modal-react" />
      <Wrapper className={noPadding ? cs.no_padding : ''}>
        <Container>
          {!withFooter && <BackButton className={cs.back} onClick={handleGoBack || handleClose} />}
          {children}
        </Container>
      </Wrapper>
      {withFooter && <Footer />}
    </ReactModal>
  ) : (
    <Modal
      className={className && className}
      containerClassName={containerClassName && containerClassName}
      crossWithShadow={crossWithShadow}
      handleGoBack={handleGoBack}
      isOpen={isOpen as boolean}
      onCloseClick={handleClose}
      withGoBack={withGoBack}
    >
      {children}
    </Modal>
  );
};
